package org.oneblog.data.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrQuery.SortClause;
import org.apache.solr.client.solrj.impl.LBHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.oneblog.data.bean.ArticleAlbum;
import org.oneblog.data.fields.ArticleAlbumField;
import org.oneblog.data.query.AlbumQuery;
import org.oneblog.data.service.IArticleAlbumSolrService;
import org.oneblog.data.util.QueryStringBuilder;
import org.oneblog.data.util.SolrQueryUtil;
import org.oneblog.data.util.StringTools;
import org.springframework.stereotype.Service;

@Service("articleAlbumSolrService")
public class ArticleAlbumSolrServiceImpl implements IArticleAlbumSolrService {

	@Override
	public int upsertAlbum(ArticleAlbum album) {
		if(album == null) {
			return 0;
		}
		
		String albumId = album.getAlbumId();
		if(StringUtils.isEmpty(albumId)) {//新增
			return insertArticleAlbum(album);
		} else {//更新
			return updateArticleAlbum(album);
		}
	}
	
	private int insertArticleAlbum(ArticleAlbum album) {
		album.setAlbumId(StringTools.randomUUID());
		album.setCreateTime(System.currentTimeMillis());
		
		SolrInputDocument document = album.createDocument();

		return addDocumentToServer(document);
	}
	
	private int updateArticleAlbum(ArticleAlbum album) {
		
		ArticleAlbum old = getArticleAlbum(album.getAlbumId());
		if(old == null) {
			return 0;
		}
		
		old.setAlbumName(album.getAlbumName());
		old.setInfo(album.getInfo());
		old.setLinks(album.getLinks());
		old.setLogo(album.getLogo());
		if(old.getCreateTime() == null || old.getCreateTime() < 1000) {
			old.setCreateTime(System.currentTimeMillis());
		}
		
		SolrInputDocument document = old.createDocument();
		
		return addDocumentToServer(document);
	}
	
	private int addDocumentToServer(SolrInputDocument in) {
		try {
			if(in == null) {
				return 0;
			}
			articleAlbumSolrServer.add(in);
			
			articleAlbumSolrServer.commit();
			
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	@Resource(name = "articleAlbumSolrServer")
	private LBHttpSolrServer articleAlbumSolrServer;

	@Override
	public ArticleAlbum getArticleAlbum(String id) {

		try {
			SolrQuery query = new SolrQuery(ArticleAlbumField.DATA_ID + ":" + id);
			
			QueryResponse queryResponse = articleAlbumSolrServer.query(query);
			
			SolrDocumentList results = queryResponse.getResults();
			if(results.size() <= 0) {
				return null;
			}
			for(SolrDocument d : results) {
				ArticleAlbum album = ArticleAlbum.createFromDocument(d);
				
				return album;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public List<ArticleAlbum> getAlbums(AlbumQuery q) {

		try {
			QueryStringBuilder builder = new QueryStringBuilder("");
			
			Integer viewDefuncted = q.getViewDefuncted();
			if(viewDefuncted != null && viewDefuncted == 1) {
				//目前只有两个状态，这里是查看所有，可以不拼接
				builder.addSubQuery(SolrQueryUtil.buildQuery(Arrays.asList(0, 1), ArticleAlbumField.DEFUNCT, "OR"));
			} else {
				//只查看 defunct = 0
				builder.addSubQuery(ArticleAlbumField.DEFUNCT, 0);
			}
			
			SolrQuery query = new SolrQuery(builder.buildAndQueryString());
			//排序
			query.addSort(new SortClause(ArticleAlbumField.DEFUNCT, ORDER.asc));
			query.addSort(new SortClause(ArticleAlbumField.CREATE_TIME, ORDER.desc));
			
			query.setStart(q.getFirst());
			query.setRows(q.getMax());
			
			QueryResponse queryResponse = articleAlbumSolrServer.query(query);
			
			SolrDocumentList results = queryResponse.getResults();
			if(results.size() <= 0) {
				return null;
			}
			List<ArticleAlbum> albums = new ArrayList<>(results.size());
			for(SolrDocument d : results) {
				ArticleAlbum album = ArticleAlbum.createFromDocument(d);
				
				albums.add(album);
			}
			return albums;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
    @Override
    public int updateAlbumDefunct(String id, int defunct) {
        if(StringUtils.isBlank(id)) {
            return 0;
        }
        
        SolrInputDocument updateDoc = new SolrInputDocument();

        updateDoc.setField(ArticleAlbumField.DATA_ID, id);
        
        Map<String, Object> updateMap = new HashMap<String, Object>();
        updateMap.put("set", defunct);
        updateDoc.setField(ArticleAlbumField.DEFUNCT, updateMap);
        
        try {
            articleAlbumSolrServer.add(updateDoc);
            articleAlbumSolrServer.commit();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        
        return 1;
    }
}
